package com.javatip.project.queue.service;

//import com.javatip.project.Change.dataset.service.ChangeDatasetServiceImpl;
//import com.javatip.project.Change.predict.service.ChangePredictServiceImpl;
//import com.javatip.project.Change.trainMission.service.ChangeTrainMissionServiceImpl;
import com.javatip.project.deep_learning.predict.service.PredictServiceImpl;
import com.javatip.project.deep_learning.trainMission.domain.TrainMission;
import com.javatip.project.deep_learning.trainMission.service.TrainMissionServiceImpl;
import com.javatip.project.queue.repository.QueueRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.javatip.project.queue.domain.Task;
import org.springframework.transaction.annotation.Transactional;

@Service
public class QueueService {
//    @Autowired
//    private TrainMission trainMission;
    @Autowired
    private TrainMissionServiceImpl trainMissionService;
    @Autowired
    private PredictServiceImpl predictService;
//    @Autowired
//    private ChangeTrainMissionServiceImpl changeTrainMissionService;
//    @Autowired
//    private ChangePredictServiceImpl changePredictService;
    @Autowired
    private QueueRepository queueRepository;


    public Integer getTimePositionByTaskID(Integer taskID, String type) {
        Task task = queueRepository.findByTaskID(taskID,type).orElse(null);
        if (task == null) {
            return null;
        }
        return queueRepository.getTimePositionByTaskID(taskID,type) ;
    }

    public Optional<Task> getEarliestTask() {
        return queueRepository.findFirstByOrderByInTimeAsc();
    }

    @Scheduled(fixedRate = 100000) // 每 10 秒执行一次
    public void continuouslyReadEarliestTask() {
        Optional<Task> earliestTask = getEarliestTask();
        if (earliestTask.isPresent()) {
            Task task = earliestTask.get();
            System.out.println("读取到最早的任务：ID=" + task.getId() + ", 任务名=" + task.getTaskName());
            //根据任务类型和ID执行任务.
            int taskID=task.getTaskID();
            //查看任务的状态,如果是待训练,就开始训练。如果是已完成或训练异常,则从队列中删除.
            if (Objects.equals(task.getTaskType(), "segTrain")) {
                String status =trainMissionService.selectTrainMissionById(taskID).getStatus();
                if (Objects.equals(status, "已完成")||Objects.equals(status, "训练异常")) {
                    //从队列中删除
                    this.deleteTaskByTypeAndID("segTrain",taskID);
                }
                else if (Objects.equals(status, "待训练")) {
                    trainMissionService.startSingleTraining(taskID );
                }

            }

            else if  (Objects.equals(task.getTaskType(), "segPredict")) {
                String status =predictService.selectPredictById(taskID).getStatus();
                if (Objects.equals(status, "已完成")||Objects.equals(status, "训练异常")) {
                    //从队列中删除
                    deleteTaskByTypeAndID("segPredict",taskID);
                }
                else if  (Objects.equals(status, "待识别")){
                    predictService.predict(taskID);
                }


            }
//            else if  (Objects.equals(task.getTaskType(), "cdTrain")) {
//                String status =changeTrainMissionService.selectChangeTrainMissionById(taskID).getStatus();
//                if (Objects.equals(status, "已完成")||Objects.equals(status, "训练异常")) {
//                    //从队列中删除
//                    deleteTaskByTypeAndID("cdTrain",taskID);
//                }
//                else if (Objects.equals(status, "待训练"))  {
//                    changeTrainMissionService.startSingleTraining(taskID );
//                }
//
//            }
//            else if  (Objects.equals(task.getTaskType(), "cdPredict")) {
//                String status =changePredictService.selectPredictById(taskID).getStatus();
//                if (Objects.equals(status, "已完成")||Objects.equals(status, "训练异常")) {
//                    //从队列中删除
//                    deleteTaskByTypeAndID("cdPredict",taskID);
//                }
//                else if (Objects.equals(status, "待识别")) {
//                    changePredictService.predict(taskID);
//                }
//
//            }
            // 可以在这里添加处理该任务的逻辑，例如将其从队列中移除
//            queueRepository.delete(task);
        } else {
            System.out.println("队列中没有任务记录。");
        }
    }

    @Transactional
    public String saveTask(Task task) {
        try {
            queueRepository.save(task);
            return "OK";
        } catch (Exception e) {
            e.printStackTrace();

            return "Error";
        }


    }

    public List<Task> getAllTasksInOrder() {
        return queueRepository.findAllByOrderByInTimeAsc();
    }

    public Task removeFirstTask() {
        List<Task> tasks = getAllTasksInOrder();
        if (!tasks.isEmpty()) {
            Task firstTask = tasks.get(0);
            queueRepository.deleteById(firstTask.getId());
            return firstTask;
        }
        return null;
    }

    public int deleteTaskByTypeAndID(String taskType, int taskID) {
        return queueRepository.deleteByTaskTypeAndTaskID(taskType, taskID);
    }
}